package com.icode.web.controller.order;

import com.icode.core.dto.house.AgreementDTO;
import com.icode.core.dto.house.HouseInfoDTO;
import com.icode.core.dto.order.OrderDTO;
import com.icode.core.dto.order.ReFundDTO;
import com.icode.core.model.order.Order;
import com.icode.core.model.order.ReFund;
import com.icode.core.model.user.User;
import com.icode.core.shared.AlipayHandle;
import com.icode.core.shared.JodaTimeUtils;
import com.icode.core.shared.OrderHandle;
import com.icode.core.shared.SecurityUtil;
import com.icode.service.house.HouseService;
import com.icode.service.order.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: xianfei
 * Date: 15-1-20
 * Time: 下午9:00
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private HouseService houseService;


    @RequestMapping(value = "form/{houseWeekGuid}", method = RequestMethod.GET)
    public ModelAndView showForm(@PathVariable String houseWeekGuid,Model model) {
        User user = SecurityUtil.currentUser();
        String phoneNum = user.getUsername();  //从申购页面获取
        OrderDTO orderDTO = orderService.createOrder(houseWeekGuid, phoneNum);
        orderDTO.setHouseWeekGuid(houseWeekGuid);
        HouseInfoDTO houseInfoDTO =orderDTO.getHouseInfoDTO();
        AgreementDTO agreementDTO = houseService.getAgreementDTOByHouseInfoDTO(houseInfoDTO);
        model.addAttribute("agreementDTO",agreementDTO);
        return new ModelAndView("front/orders/order", "orderDTO", orderDTO);
    }

    @RequestMapping(value = "form", method = RequestMethod.POST)
    public void payPage(OrderDTO orderDTO, String houseWeekGuid, PrintWriter out) {
        Order order = orderService.saveOrUpdateOrder(orderDTO, houseWeekGuid);
        AlipayHandle.alipay(order, out);
    }

    @RequestMapping(value = "toReFund/{orderGuid}", method = RequestMethod.GET)
    public String toReFund(@PathVariable String orderGuid, Model model) {
        Order order = orderService.findOrderByGuid(orderGuid);
        model.addAttribute("orderGuid", orderGuid);
        model.addAttribute("orderPrice", order.orderInfo().totalPrice());
        return "front/alipay/reFund";
    }

    @RequestMapping(value = "addReFund/{orderGuid}", method = RequestMethod.POST)
    public String reFund(@PathVariable String orderGuid, String WIDprice, String WIDdetail_data) throws UnsupportedEncodingException {
        Order order = orderService.findOrderByGuid(orderGuid);
        String refundDate = JodaTimeUtils.getTime("yyyy-MM-dd HH:mm:ss");
        String batch_no = JodaTimeUtils.getTime("yyyyMMdd") + JodaTimeUtils.getSerial();
        String detailData = order.orderInfo().alipayTradeNo() + "^" + WIDprice + "^" + new String(WIDdetail_data.getBytes("utf-8"), "utf-8");  //退款价格从前台页面获取
        ReFund reFund = new ReFund(order, refundDate, batch_no, order.orderInfo().alipayTradeNo(), WIDprice, detailData, "待审核");
        orderService.addReFund(reFund);
        orderService.changeOrderStatusByGuid(orderGuid, "已申请退款");
        return "redirect:/order/order_manager";
    }

    @RequestMapping(value = "reFundList", method = RequestMethod.GET)
    public String reFundList(Model model) {
        List<ReFundDTO> reFundDTOs = orderService.findAllReFund();
        model.addAttribute("reFundDTOs", reFundDTOs);
        return "back/reFund/reFund";
    }

    @RequestMapping(value = "doReFund/{reFundGuid}", method = RequestMethod.GET)
    public void doReFund(@PathVariable String reFundGuid, PrintWriter out) {
        ReFund reFund = orderService.findReFundByGuid(reFundGuid);
        AlipayHandle.reFund(out, reFund.detailData());
    }

    @RequestMapping(value = "doBatchReFund/{reFundGuids}", method = RequestMethod.GET)
    public void doBatchReFund(@PathVariable String reFundGuids, PrintWriter out) {
        String[] guids = reFundGuids.split(",");
        String detailData = AlipayHandle.getDetailData(guids, orderService);
        AlipayHandle.batchRefund(out, detailData, String.valueOf(guids.length));
    }

    @RequestMapping(value = "refundNotify_url", method = RequestMethod.POST)
    public void refundNotify_url(HttpServletRequest request, PrintWriter out) {
        AlipayHandle.refundNotify_url(request, orderService, out);
    }

    @RequestMapping(value = "return_url", method = RequestMethod.GET)
    public String return_url(HttpServletRequest request, PrintWriter out) {
        Map<String, Object> result = AlipayHandle.return_url(request, orderService, out);
        boolean isSuccess = (boolean) result.get("success");
        if (isSuccess) {
            String orderGuid = (String) result.get("orderGuid");
            orderService.initMyHouse(orderGuid);
            return "redirect:/my_house/show";
        }
        return "redirect:/order/order_manager";
    }

    @RequestMapping(value = "notify_url", method = RequestMethod.POST)
    public void notify_url(HttpServletRequest request, PrintWriter out) {
        AlipayHandle.notify_url(request, orderService, out);
    }

    @RequestMapping(value = "payOrder/{orderGuid}", method = RequestMethod.GET)
    public void payOrder(@PathVariable String orderGuid, PrintWriter out) {
        Order order = orderService.findOrderByGuid(orderGuid);
        String orderTime = order.orderInfo().time();
        if (JodaTimeUtils.isTimeOut(orderTime)) {       //判断订单是否失效
            orderService.revokeOrderByGuid(orderGuid);
        } else {
            AlipayHandle.alipay(order, out);
        }
    }

    @RequestMapping(value = "order_manager", method = RequestMethod.GET)
    public String orderManager(Model model) {
        User user = SecurityUtil.currentUser();
        String username = user.getUsername(); //从申购页面获取
        List<OrderDTO> orderDTOs = orderService.findOrderByUsersInfo(username);
        model.addAttribute("orderDTOs", orderDTOs);
        return "front/orders/orderManager";
    }

    @RequestMapping(value = "delete/{guid}", method = RequestMethod.GET)
    public String deleteOrder(@PathVariable String guid) {
        orderService.deleteOrdersByGuid(guid);
        return "redirect:/order/order_manager";
    }

    @RequestMapping(value = "deleteMore/{guids}", method = RequestMethod.GET)
    public String deleteOrdersByList(@PathVariable String guids) {
        String[] guidArray = guids.split(",");
        orderService.deleteOrdersByList(guidArray);
        return "redirect:/order/order_manager";
    }

    @RequestMapping(value = "ajaxRefundData/{status}", method = RequestMethod.GET)
    public void ajaxRefundData(@PathVariable String status, HttpServletResponse response) {
        OrderHandle.ajaxRefundData(status, orderService, response);
    }

    @RequestMapping(value = "reject/{refundGuid}")
    public String rejectRefund(@PathVariable String refundGuid) {
        orderService.changeReFundStatusByGuid(refundGuid, "已驳回");
        ReFund reFund = orderService.findReFundByGuid(refundGuid);
        orderService.changeOrderStatusByGuid(reFund.order().guid(), "已驳回");
        return "redirect:/order/reFundList";
    }

}
